package org.grayrabbit.cloud.core.beans;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author sys53
 * @version 1.0
 * @created 12-7-2011 15:58:52
 */
public class Creator {

	private static ConcurrentMap<String, Class<?>> classes = new ConcurrentHashMap<String, Class<?>> ();
	private static final Logger logger = LoggerFactory.getLogger(Creator.class);

	/**
	 * 
	 * @param className
	 * @throws CreatorException 
	 */
	@SuppressWarnings("unchecked")
	public static <T> T create(String className) throws CreatorException {
		assert (className != null);
		if (className == null)
			throw new NullPointerException();
		try {
			Class<?> c = (Class<T>) classes.get(className);
			if (c == null) {
				c = Class.forName(className);
				assert (c != null);
				classes.putIfAbsent(className, c);
				c = (Class<?>) classes.get(className);
			}
			return (T) c.newInstance();
		} catch (ClassNotFoundException e) {
			logger.error("class not found",e);
			throw new CreatorException(e);
		} catch (IllegalAccessException e) {
			throw new CreatorException(e);
		} catch (InstantiationException e) {
			throw new CreatorException(e);
		} catch (Throwable e) {
			throw new CreatorException(e);
		}
		
	}

}